package cn.otrue.patienthealthmanager.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.adapter.TextAdapter;
import cn.otrue.patienthealthmanager.bean.PlusModel;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.view.MyGridView;
import cn.otrue.patienthealthmanager.view.SwitchButton;

/**
 * 主页->健康计划->血压管理
 * 
 * @author G
 * 
 */
public class PlusManagerActivity extends BaseActivity implements
		OnItemClickListener {
	private PlusModel plusModel;
	private TextView tv_title_back;
	private TextView tv_title_title;
	private String beginTime = "";
	private String endTime = "";
	private List<Map<String, String>> weekData = new ArrayList<Map<String, String>>();
	private TextAdapter weekAdapter;
	private MyGridView gv_plus_week;
	private TextView tv_title_other;
	private MyGridView gv_plus_manager_times;
	private MyTimeAdapter timesAdapter;
	/** 测量时间 */
	private List<String> timesData;
	private ImageView iv_plus_manager_reduction;
	private TextView tv_plus_manager_times;
	private ImageView iv_plus_manager_add;
	private TextView tv_plus_manager_note;
	private SwitchButton sb_plus_manager_colock;
	private EditText et_plus_begin_time;
	private EditText et_plus_end_time;

	// 开始时间选择框
	private DatePickerDialog beginDateDialog;
	// 结束时间选择框
	private DatePickerDialog endDateDialog;
	// 开始时间
	private Calendar beginCalendar = Calendar.getInstance();
	// 结束时间
	private Calendar endCalendar = Calendar.getInstance();

	private String[] strArr = { "06:30", "09:00", "11:30", "14:00", "17:30",
			"20:00" };
	private int type;
	private EditText et_plus_manager_note;
	private SimpleDateFormat sdf;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_plus_manager);
		sdf = new SimpleDateFormat("yyyy-MM-dd");
		getData();
		initView();

	}

	private void getData() {
		Intent intent = getIntent();
		type = intent.getIntExtra("type", -1);
		String dataStr = intent.getStringExtra("data");
		if (TextUtils.isEmpty(dataStr)) {
			plusModel = new PlusModel();
		} else {
			plusModel = HttpServer.gson.fromJson(dataStr, PlusModel.class);
		}

		timesData = new ArrayList<String>();

		if (TextUtils.isEmpty(plusModel.getMesuretime())) {
			plusModel.setMesuretime(strArr[0]);
		}
		String[] timeArr = plusModel.getMesuretime().split("  ");
		for (int i = 0; i < timeArr.length; i++) {
			timesData.add(timeArr[i]);
		}

		for (int i = 0; i < 7; i++) {
			Map<String, String> week = new HashMap<String, String>();
			week.put("diseasename", MyConst.WEEK[i]);
			week.put("weekid", i + "");
			week.put("state", "0");
			weekData.add(week);
		}

		if (plusModel.getWeekList() != null) {
			for (int i = 0; i < plusModel.getWeekList().size(); i++) {
				int eachOne = Integer.parseInt(plusModel.getWeekList().get(i));
				for (int j = 0; j < weekData.size(); j++) {
					if (eachOne == Integer.parseInt(weekData.get(j).get(
							"weekid"))) {
						weekData.get(j).put("state", "1");
					}
				}
			}
		}

	}

	private void initView() {

		initTitleBar();

		gv_plus_week = (MyGridView) findViewById(R.id.gv_plus_week);
		gv_plus_manager_times = (MyGridView) findViewById(R.id.gv_plus_manager_times);
		iv_plus_manager_reduction = (ImageView) findViewById(R.id.iv_plus_manager_reduction);
		iv_plus_manager_add = (ImageView) findViewById(R.id.iv_plus_manager_add);
		tv_plus_manager_times = (TextView) findViewById(R.id.tv_plus_manager_times);
		tv_plus_manager_note = (TextView) findViewById(R.id.tv_plus_manager_note);
		et_plus_manager_note = (EditText) findViewById(R.id.et_plus_manager_note);
		sb_plus_manager_colock = (SwitchButton) findViewById(R.id.sb_plus_manager_colock);
		et_plus_begin_time = (EditText) findViewById(R.id.et_plus_begin_time);
		et_plus_end_time = (EditText) findViewById(R.id.et_plus_end_time);

		sb_plus_manager_colock.setOnClickListener(this);

		switch (type) {
		case MyConst.BLANK_PLAN:
		case MyConst.CHANGE_PLAN:
			et_plus_begin_time.setOnClickListener(this);
			et_plus_end_time.setOnClickListener(this);
			timesAdapter = new MyTimeAdapter(this, timesData, true);
			et_plus_manager_note.setVisibility(View.VISIBLE);
			gv_plus_week.setOnItemClickListener(this);
			iv_plus_manager_add.setOnClickListener(this);
			iv_plus_manager_reduction.setOnClickListener(this);
			tv_plus_manager_note.setVisibility(View.GONE);
			if (!TextUtils.isEmpty(plusModel.getNote())) {
				et_plus_manager_note.setText(plusModel.getNote());
			}
			break;
		case -1:
		case MyConst.SHOW_PLAN:
			timesAdapter = new MyTimeAdapter(this, timesData, false);
			iv_plus_manager_reduction.setVisibility(View.GONE);
			iv_plus_manager_add.setVisibility(View.GONE);
			tv_title_other.setVisibility(View.GONE);
			et_plus_manager_note.setVisibility(View.GONE);
			if (!TextUtils.isEmpty(plusModel.getNote())) {
				tv_plus_manager_note.setText(plusModel.getNote());
			}
			break;
		}

		gv_plus_manager_times.setAdapter(timesAdapter);
		weekAdapter = new TextAdapter(this, weekData);
		gv_plus_week.setAdapter(weekAdapter);
		gv_plus_week.setSelector(new ColorDrawable(Color.TRANSPARENT));

		tv_plus_manager_times.setText(timesData.size() + "次/天");

		try {
			if (!TextUtils.isEmpty(plusModel.getPlan_begintime())
					&& !TextUtils.isEmpty(plusModel.getPlan_endtime())) {
				et_plus_begin_time.setText(plusModel.getPlan_begintime()
						.substring(0, 10));
				et_plus_end_time.setText(plusModel.getPlan_endtime().substring(
						5, 10));
				beginTime = plusModel.getPlan_begintime();
				endTime = plusModel.getPlan_endtime();
				beginCalendar.setTime(sdf.parse(plusModel.getPlan_begintime()));
				endCalendar.setTime(sdf.parse(plusModel.getPlan_endtime()));
			}
		} catch (ParseException e) {

		}

	}

	private void initTitleBar() {

		tv_title_back = (TextView) findViewById(R.id.tv_title_back);
		tv_title_back.setVisibility(View.VISIBLE);
		tv_title_back.setOnClickListener(this);
		tv_title_title = (TextView) findViewById(R.id.tv_title_title);
		tv_title_title.setText(getString(R.string.plus_manager));
		tv_title_other = (TextView) findViewById(R.id.tv_title_other);
		tv_title_other.setVisibility(View.VISIBLE);
		tv_title_other.setOnClickListener(this);
		tv_title_other.setText(getString(R.string.community_fatie));

	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.tv_title_back:
			finish();
			break;
		case R.id.tv_title_other:
			resultData();
			break;
		case R.id.sb_plus_manager_colock:
			sb_plus_manager_colock.changeOpen();
			break;
		case R.id.et_plus_begin_time:

			beginDateDialog = new DatePickerDialog(this, BeginDateSet,
					beginCalendar.get(Calendar.YEAR),
					beginCalendar.get(Calendar.MONTH),
					beginCalendar.get(Calendar.DAY_OF_MONTH));
			beginDateDialog.setTitle("开始时间");
			beginDateDialog.show();
			break;

		case R.id.et_plus_end_time:

			endDateDialog = new DatePickerDialog(this, EndDateSet,
					endCalendar.get(Calendar.YEAR),
					endCalendar.get(Calendar.MONTH),
					endCalendar.get(Calendar.DAY_OF_MONTH));
			endDateDialog.setTitle("结束时间");
			endDateDialog.show();

			break;

		case R.id.iv_plus_manager_reduction:
			if (timesData.size() == 1) {
				Toast.makeText(this, "次数不能低于1", 0).show();
			} else {

				timesData.remove(timesData.size() - 1);
				tv_plus_manager_times.setText(timesData.size() + "次/天");
				timesAdapter.notifyDataSetChanged();

			}
			break;
		case R.id.iv_plus_manager_add:
			if (timesData.size() >= 6) {
				Toast.makeText(this, "最多不能超过6次", 0).show();
			} else {
				timesData.add(strArr[timesData.size()]);
				tv_plus_manager_times.setText(timesData.size() + "次/天");
				timesAdapter.notifyDataSetChanged();
			}
			break;
		default:
			break;
		}

	}

	private void resultData() {
		List<String> weekList = new ArrayList<String>();
		for (int i = 0; i < weekData.size(); i++) {
			if (weekData.get(i).get("state").equals("1")) {
				weekList.add(weekData.get(i).get("weekid").toString());
			}
		}

		plusModel.setWeekList(weekList);

		int num = 0;
		Set<String> uniqueSet = new HashSet<String>(timesData);
		for (String temp : uniqueSet) {
			int cnum = Collections.frequency(timesData, temp);
			if (cnum > 1) {
				num++;
			}
		}

		String timesStr = "";
		for (int i = 0; i < timesData.size(); i++) {
			timesStr = timesStr + "  " + timesData.get(i);
		}

		timesStr = timesStr.substring(2);
		plusModel.setMesuretime(timesStr);
		plusModel.setPlan_begintime(beginTime);
		plusModel.setPlan_endtime(endTime);
		plusModel.setNote(et_plus_manager_note.getText().toString());

		if (TextUtils.isEmpty(beginTime)) {
			Toast.makeText(this, "请选择开始时间", 0).show();
		} else if (TextUtils.isEmpty(endTime)) {
			Toast.makeText(this, "请选择结束时间", 0).show();
		} else if (weekList.size() < 1) {
			Toast.makeText(this, "请选择重复时间", 0).show();
		} else if (num > 0) {
			Toast.makeText(this, "不能有相同的提醒时间", 0).show();
		} else {

			Intent intent = new Intent();
			intent.putExtra("plusData", HttpServer.gson.toJson(plusModel));
			setResult(MyConst.PLUS_RESULT, intent);
			finish();
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		String state = weekData.get(position).get("state");
		if (TextUtils.isEmpty(state) || state.equals("0")) {
			weekData.get(position).put("state", "1");
		} else {
			weekData.get(position).put("state", "0");
		}

		weekAdapter.notifyDataSetChanged();

	}

	public class MyTimeAdapter extends BaseAdapter {

		private List<String> data;
		private Context context;
		private LayoutInflater inflater;
		private boolean isClick;

		public MyTimeAdapter(Context context, List<String> data, boolean isClick) {
			super();
			this.data = data;
			this.context = context;
			inflater = LayoutInflater.from(this.context);
			this.isClick = isClick;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {

			TextView myText = (TextView) inflater.inflate(
					R.layout.item_plus_text, null);
			myText.setTag(arg0);
			if (isClick) {
				myText.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						SetTimeDialog std = new SetTimeDialog((TextView) v);
						std.show(((Activity) context).getFragmentManager(),
								"timePicker");

					}
				});
			}
			myText.setText(data.get(arg0));
			return myText;
		}

		class SetTimeDialog extends DialogFragment implements
				TimePickerDialog.OnTimeSetListener {

			TextView tv;

			public SetTimeDialog(TextView tv) {
				super();
				this.tv = tv;
			}

			@SuppressLint("NewApi")
			public Dialog onCreateDialog(Bundle savedInstanceState) {

				final Calendar c = Calendar.getInstance();
				int hour = c.get(Calendar.HOUR_OF_DAY);
				int minute = c.get(Calendar.MINUTE);

				String dateStr = tv.getText().toString();
				String[] dateArr = dateStr.split(":");

				if (dateArr.length == 2) {
					hour = Integer.parseInt(dateArr[0]);
					minute = Integer.parseInt(dateArr[1]);
				}
				TimePickerDialog tpd = new TimePickerDialog(getActivity(),
						this, hour, minute,
						DateFormat.is24HourFormat(getActivity()));
				return tpd;
			}

			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

				String timeStr = timeFormat(hourOfDay) + ":"
						+ timeFormat(minute);
				tv.setText(timeStr);
				int tag = Integer.parseInt(tv.getTag().toString());

				data.set(tag, timeStr);

			}

			private String timeFormat(int time) {
				if (time < 10) {
					return "0" + time;
				}
				return time + "";
			}

		}
	}

	DatePickerDialog.OnDateSetListener BeginDateSet = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// 每次保存设置的日期

			beginCalendar.set(Calendar.YEAR, year);
			beginCalendar.set(Calendar.MONTH, monthOfYear);
			beginCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			beginTime = year + "-" + timeFormat(monthOfYear + 1) + "-"
					+ timeFormat(dayOfMonth);

			et_plus_begin_time.setText(beginTime);

		}
	};

	DatePickerDialog.OnDateSetListener EndDateSet = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			int byear = beginCalendar.get(Calendar.YEAR);
			int bmonth = beginCalendar.get(Calendar.MONTH);
			int bday = beginCalendar.get(Calendar.DAY_OF_MONTH);

			if ((byear * 365 + bmonth * 30 + bday) >= (year * 365 + monthOfYear
					* 30 + dayOfMonth)) {
				Toast.makeText(PlusManagerActivity.this, "结束时间不能小于起始时间", 0)
						.show();

				endCalendar = Calendar.getInstance();
				et_plus_end_time.setText("");

			} else {
				endCalendar.set(Calendar.YEAR, year);
				endCalendar.set(Calendar.MONTH, monthOfYear);
				endCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				beginTime = byear + "-" + timeFormat(bmonth + 1) + "-"
						+ timeFormat(bday);
				endTime = year + "-" + timeFormat(monthOfYear + 1) + "-"
						+ timeFormat(dayOfMonth);

				et_plus_end_time.setText(timeFormat(monthOfYear + 1) + "-"
						+ timeFormat(dayOfMonth));

			}

		}
	};

	private String timeFormat(int time) {
		if (time < 10) {
			return "0" + time;
		}
		return time + "";
	}

}
